import { defineStore } from 'pinia'

interface UserInfo {
    name: string
    avatar: string
    token: string
}

export const useAuthStore = defineStore('auth', {
    state: () => ({
        isAuthenticated: false,
        user: null as UserInfo | null,
        token: ''
    }),
    actions: {
        login(user: UserInfo) {
            this.isAuthenticated = true
            this.user = user
            this.token = user.token
            localStorage.setItem('token', user.token)
            localStorage.setItem('userInfo', JSON.stringify(user))
        },
        logout() {
            this.isAuthenticated = false
            this.user = null
            this.token = ''
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
        },
        updateUserInfo(userInfo: Partial<UserInfo>) {
            if (this.user) {
                this.user = { ...this.user, ...userInfo }
                localStorage.setItem('userInfo', JSON.stringify(this.user))
            }
        },
        initAuth() {
            const token = localStorage.getItem('token')
            const userInfo = localStorage.getItem('userInfo')

            if (token && userInfo) {
                try {
                    const user = JSON.parse(userInfo)
                    this.isAuthenticated = true
                    this.user = user
                    this.token = token
                } catch (error) {
                    // 如果解析失败，清除无效数据
                    this.logout()
                }
            }
        }
    }
})
